package com.yike.user.lkl.incoming;


import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.yike.common.exception.BusinessException;
import com.yike.common.redis.RedisUtil;
import com.yike.user.lkl.LklSdkProperties;
import com.yike.user.lkl.incoming.request.IncomingFiles;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author whc
 * @date 2025/5/8 10:00
 * 获取进件token
 */

@Slf4j
@Data
@Component
public class IncomingCommon {


    @Resource
    private  LklIncomingProperties properties;



    @Resource
    private RedisUtil redisUtil;

    public String sendPostRequestFile(String urlString,IncomingFiles incomingFiles) throws IOException {
        urlString =  properties.getUrl() + urlString;
        String Authorization = "bearer " + this.getToken();
        HttpResponse httpResponse = HttpRequest.post(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .form("file", incomingFiles.getFile())
                .form("sourcechnl", incomingFiles.getSourcechnl())
                .form("isOcr", incomingFiles.getIsOcr())
                .form("imgType", incomingFiles.getImgType())
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        if(status >= 400){
            return null;
        }
        return body;
    }

    public String sendPostRequestJson(String urlString,String data) throws IOException {
        urlString =  properties.getUrl() + urlString;
        String Authorization = "bearer " + this.getToken();

        HttpResponse httpResponse = HttpRequest.post(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .body(data)
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        log.info("请求进件相关响应参数，status:{},body:{}",status,body);
        if(status >= 400){
           // return null;
           JSONObject jsonObject = new JSONObject(body);
           throw new BusinessException(500, jsonObject.getStr("message"));
        }

        return body;
    }



    /**
     * 登录后的请求
     * @param urlString
     * @param data
     * @return
     * @throws IOException
     */
    public String sendPostRequestLoginJson(String urlString,String data) throws IOException {
        urlString =  properties.getUrl() + urlString;
        String Authorization = "bearer " + this.getTokenLogin();

        HttpResponse httpResponse = HttpRequest.post(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .body(data)
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        log.info("请求进件相关响应参数，status:{},body:{}",status,body);
        if(status >= 400){
            return null;
            //JSONObject jsonObject = new JSONObject(body);
            //throw new BusinessException(500, jsonObject.getStr("message"));
        }

        return body;
    }




    public String sendGetRequest(String urlString) throws IOException {
        urlString =  properties.getUrl() + urlString;
        String Authorization = "bearer " + this.getToken();

        HttpResponse httpResponse = HttpRequest.get(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        log.info("请求进件相关响应参数，status:{},body:{}",status,body);
        if(status >= 400){
            return null;
        }
        return body;
    }
    public String sendPostRequestJsonByUrlThirdParty(String urlString,String data) throws IOException {
        urlString =  properties.getUrlThirdParty() + urlString;
        String Authorization = "bearer " + this.getToken();
        HttpResponse httpResponse = HttpRequest.post(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .body(data)
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        if(status >= 400){
            return null;
        }
        return body;
    }




    public String sendGetRequest(String urlString,String data) throws IOException {
        urlString =  properties.getUrl() + urlString;
        String Authorization = "bearer " + this.getToken();
        HttpResponse httpResponse = HttpRequest.get(urlString)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .form(data)
                .timeout(20000)//超时，毫秒
                .execute();
        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
        if(status >= 400){
            return null;
        }
        return body;
    }


    public String getToken() throws IOException {
        //如果redis里存在token则拿redis的
        String key = "IncomingToken"; //redis key
        if(properties.getApiType().equals("prod")){
            key = "IncomingTokenProd";
        }
        if(redisUtil.hasKey(key)){
            return redisUtil.get(key).toString();
        }
        String jsonResponse = this.queryToken();
        JSONObject jsonObject = new JSONObject(jsonResponse);
        System.out.println(jsonObject);
        if (jsonObject.containsKey("access_token")) {
            String token = jsonObject.getStr("access_token");
            int expiresIn = Integer.parseInt(jsonObject.getStr("expires_in"));
            expiresIn = expiresIn - 60 *5; //减去5分钟，即将过期直接请求新的token
            redisUtil.set(key,token,expiresIn);
            return token;
        }else {
            return null;
        }

    }


    public String getTokenLogin() throws IOException {
        //如果redis里存在token则拿redis的
        String key = "IncomingLoginToken"; //redis key
        if(redisUtil.hasKey(key)){
            return redisUtil.get(key).toString();
        }
        String jsonResponse = this.loginToken();
        JSONObject jsonObject = new JSONObject(jsonResponse);
        System.out.println(jsonObject);
        if (jsonObject.containsKey("access_token")) {
            String token = jsonObject.getStr("access_token");
            int expiresIn = Integer.parseInt(jsonObject.getStr("expires_in"));
            expiresIn = expiresIn - 60 *5; //减去5分钟，即将过期直接请求新的token
            redisUtil.set(key,token,expiresIn);
            return token;
        }else {
            return null;
        }

    }


    public String  loginToken() throws IOException {
        String api = "/sit/htkauth/oauth/token";
        if (properties.getApiType().equals("prod")){
            api = "/auth/oauth/token";
        }
        String Authorization = "Basic " + Base64.getEncoder().encodeToString(( "client_id:" + properties.getClientSecret()).getBytes());
        String urlInfo = properties.getUrl() + api;
        Map<String ,String> map = new HashMap<>();
        map.put("grant_type","password");
        map.put("username",properties.getUsername());
        map.put("password",properties.getPassword());

        HttpResponse httpResponse = HttpRequest.get(urlInfo)
                .header(Header.AUTHORIZATION, Authorization)//头信息，多个头信息多次调用此方法即可
                .form(JSON.toJSONString(map))
                .timeout(20000)//超时，毫秒
                .execute();

        int status = httpResponse.getStatus(); //获取响应码
        String body = httpResponse.body(); //获取响应内容
//        if(status >= 400){
//            return null;
//        }
        return body;

    }


    public String  queryToken() throws IOException {
        String api = "/sit/htkauth/oauth/token";
        if (properties.getApiType().equals("prod")){
            api = "/auth/oauth/token";
        }
        String urlInfo = properties.getGetTokenUrl() + api + "?" + "grant_type=" + properties.getGrantType() + "&client_id=" + properties.getClientId() + "&client_secret=" + properties.getClientSecret();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(urlInfo)
                .post(RequestBody.create(null, new byte[0]))
                .build();
        Response response = client.newCall(request).execute();

        return response.body().string();

    }






}
